package com.ji.storm.TestStorm.bolt;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;

import com.ji.storm.TestStorm.cons.Const;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;

public class ReportBolt extends BaseRichBolt {
	private Map<String, Long> wordCount;

	public static final Logger logger = Logger.getLogger(SplitBolt.class);

	@Override
	public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
		this.wordCount = new HashMap<>();
	}

	@Override
	public void execute(Tuple input) {
		String word = input.getStringByField(Const.WORD);
		Long count = input.getLongByField(Const.COUNT);
		logger.info("--" + word + "|" + count);
		// TestStringWriter.writeToTxt("--" + word + "|" + count);
		wordCount.put(word, count);
	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer declarer) {

	}

	@Override
	public void cleanup() {
		System.out.println("---COUNT---");
		Iterator<String> it = wordCount.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			Long count = wordCount.get(key);
			System.out.println(key + "=" + count);
		}
		System.out.println("");
	}
}
